package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.CategoryBrandRelationDao;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.BrandDao;
import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();

//        查询条件
        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)){
//            根据key进行精确查询brand_id和模糊查询name
            wrapper.eq("brand_id",key).or().like("name",key);
        }

        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    /**
     * 修改品牌名称时，需要顺带修改品牌类别关联表中的名称
     * @param brand
     */
    @Transactional
    @Override
    public void updateByFild(BrandEntity brand) {

//        查询品牌类别关联表中的名称
        CategoryBrandRelationEntity categoryBrandRelationEntity = categoryBrandRelationService.getOne(new QueryWrapper<CategoryBrandRelationEntity>().eq("brand_id", brand.getBrandId()));
        if (null != categoryBrandRelationEntity){
//            如果不相同，说明品牌已修改名称
            if (!brand.getName().equals(categoryBrandRelationEntity.getBrandName())){
                categoryBrandRelationEntity.setBrandName(brand.getName());
//            修改品牌类别关联表中的品牌名称
                categoryBrandRelationService.updateBrand(brand.getBrandId(),brand.getName());
            }
        }
//           修改品牌信息
        this.updateById(brand);
    }

    @Override
    public List<BrandEntity> getBrandsByIds(List<Long> brandIds) {
//        查询所有品牌
        return baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brandId",brandIds));
    }

}